package com.example.fan.airline_reservation.Adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fan.airline_reservation.MainActivity;
import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.Model.Order;
import com.example.fan.airline_reservation.Model.Passenger;
import com.example.fan.airline_reservation.Model.Temp;
import com.example.fan.airline_reservation.Model.Trip;
import com.example.fan.airline_reservation.Model.USER;
import com.example.fan.airline_reservation.QRCodeUtil;
import com.example.fan.airline_reservation.R;
import com.example.fan.airline_reservation.Traveler_Interface;
import com.example.fan.airline_reservation.fragment_class.traveler_search;
import com.example.fan.airline_reservation.fragment_class.traveler_trip;
import com.example.fan.airline_reservation.register;
import com.example.fan.airline_reservation.traveler_bookticket;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.util.V;

public class TripAdapter extends ArrayAdapter<Trip> {
    private int res;
    Dialog dia;
    Trip trip=new Trip();
    TextView state;
    TextView delaytime;
    TextView starttime;
    TextView arrivetime;
    TextView flytime;
    TextView startplace;
    TextView arriveplace;
    TextView date;
    TextView fligNO;
    TextView passenger;
    ImageView bitmap;
    Button refund;
    Button change;
    TextView objectid,orderId,isPick,account;
    Context context;
    int isCut=0;
    public TripAdapter(Context context, int resource, List<Trip> objects) {
        super(context, resource, objects);
        this.context=context;
        res=resource;
    }
    public View getView(final int position, View convertView, ViewGroup parent){
        trip=getItem(position);
        final View view= LayoutInflater.from(getContext()).inflate(res,parent,false);
        state=(TextView)view.findViewById(R.id.trip_state);
        delaytime=(TextView)view.findViewById(R.id.trip_delaytime);
        starttime=(TextView)view.findViewById(R.id.trip_Stime);
        arrivetime=(TextView)view.findViewById(R.id.trip_Atime);
        flytime=(TextView)view.findViewById(R.id.trip_flytime);
        startplace=(TextView)view.findViewById(R.id.trip_Splace);
        arriveplace=(TextView)view.findViewById(R.id.trip_Aplace);
        date=(TextView)view.findViewById(R.id.trip_Sdate);
        fligNO=(TextView)view.findViewById(R.id.trip_flyNO);
        passenger=(TextView)view.findViewById(R.id.trip_passenger);
        bitmap=(ImageView)view.findViewById(R.id.bitmap);
        refund=(Button)view.findViewById(R.id.trip_canel);
        change=(Button)view.findViewById(R.id.trip_change);
        objectid=(TextView)view.findViewById(R.id.trip_ObjectId);
        account=(TextView)view.findViewById(R.id.trip_account);
        orderId=(TextView)view.findViewById(R.id.trip_orderId);
        isPick=(TextView)view.findViewById(R.id.trip_isPick);
        if(trip.getState()=="正常候机"){
            state.setTextColor(Color.parseColor("#3f87e9"));
        }
        else if(trip.getState()=="航班延误"){
            state.setTextColor(Color.parseColor("#ffa500"));
        }
        else {
            state.setTextColor(Color.parseColor("#f65557"));
        }
        state.setText(trip.getState());
        if(trip.getDelaytime()>0){
            delaytime.setText(trip.getDelaytime()+"分钟");
        }
        objectid.setText(trip.getObjectidOr());
        starttime.setText(trip.getStarttime());
        arrivetime.setText(trip.getArrivetime());
        flytime.setText(trip.getFlytime());
        startplace.setText(trip.getStartplace());
        arriveplace.setText(trip.getArriveplace());
        date.setText(trip.getDate());
        fligNO.setText(trip.getFlightNO());
        passenger.setText(trip.getPassenger());
        orderId.setText(trip.getOrder().getObjectId());
        account.setText(trip.getAccount());
        isPick.setText(trip.isPick()+"");

        bitmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap mBitmap = QRCodeUtil.createQRCodeBitmap(getItem(position).getObjectidOr()+"", 480, 480);
                Toast.makeText(getContext(),"请扫描二维码取票",Toast.LENGTH_LONG).show();
                dia = new Dialog(getContext(), R.style.edit_AlertDialog_style);
                dia.setContentView(R.layout.bitmap_dia);
                ImageView imageView = (ImageView) dia.findViewById(R.id.diaBitmap);
                imageView.setImageBitmap(mBitmap);
                //选择true的话点击其他地方可以使dialog消失，为false的话不会消失
                dia.setCanceledOnTouchOutside(true); // Sets whether this dialog is
                Window w = dia.getWindow();
                WindowManager.LayoutParams lp = w.getAttributes();
                lp.x = 0;
                lp.y = 40;
                dia.onWindowAttributesChanged(lp);
                imageView.setOnClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dia.dismiss();
                            }
                        });
                dia.show();
            }
        });

        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
                builder.setMessage("是否改签机票？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Log.e("objectid",getItem(position).getObjectidOr()+"");

                        String bq0="select * from Order where objectId='"+getItem(position).getObjectidOr()+"'";
                        new BmobQuery<Order>().doSQLQuery(bq0, new SQLQueryListener<Order>() {
                            @Override
                            public void done(BmobQueryResult<Order> bmobQueryResult, BmobException e) {
                                Order o=bmobQueryResult.getResults().get(0);
                                Log.e("ispick",o.isTicketCollect()+"");
                                if(o.isTicketCollect()){
                                    Toast.makeText(getContext(),
                                            "您已经取票，无法进行网上改签，请前往柜台办理",Toast.LENGTH_SHORT).show();
                                }
                                else {
                                    refundtick(position);
                                    Intent intent=new Intent(context, Traveler_Interface.class);
                                    intent.putExtra("USER11",getItem(position).getUser());
                                    context.startActivity(intent);
                                    if (Activity.class.isInstance(context)) {
                                        Activity activity = (Activity) context;
                                        activity.finish();
                                    }
                                }
                            }
                        });
                    }
                });
                builder.show();
            }
        });
        refund.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(getContext());
                builder.setMessage("是否退票？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Log.e("objectid",getItem(position).getObjectidOr()+"");

                        String bq0="select * from Order where objectId='"+getItem(position).getObjectidOr()+"'";
                        new BmobQuery<Order>().doSQLQuery(bq0, new SQLQueryListener<Order>() {
                            @Override
                            public void done(BmobQueryResult<Order> bmobQueryResult, BmobException e) {
                                Order o=bmobQueryResult.getResults().get(0);
                                Log.e("ispick",o.isTicketCollect()+"");
                                if(o.isTicketCollect()){
                                    Toast.makeText(getContext(),
                                            "您已经取票，无法进行网上退票，请前往柜台办理退票手续",Toast.LENGTH_SHORT).show();
                                }
                                else {
                                    refundtick(position);
                                    Toast.makeText(getContext(),
                                            "退票成功 ，请点击刷新按钮刷新界面",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
                builder.show();
            }
        });

        return view;
    }

    private void refundtick(final int position) {
        String bq0="select * from Fight where FLIGHT='"+getItem(position).getFlightNO()+"'";
        new BmobQuery<Fight>().doSQLQuery(bq0, new SQLQueryListener<Fight>() {
            @Override
            public void done(BmobQueryResult<Fight> bmobQueryResult, BmobException e) {
                if(e==null){
                    Log.e("refund","0");
                    Fight f=new Fight();
                    f=bmobQueryResult.getResults().get(0);
                    if(f.getCurrentState()==2){
                        String bq1="select * from Fight where FLIGHT='"+getItem(position).getFlightNO()+"'";
                        Log.e("refunde0",getItem(position).getFlightNO());
                        new BmobQuery<Fight>().doSQLQuery(bq1, new SQLQueryListener<Fight>() {
                            @Override
                            public void done(BmobQueryResult<Fight> bmobQueryResult, BmobException e) {
                                if(e==null){
                                    Log.e("refund","0");
                                    Fight f=new Fight();
                                    f=bmobQueryResult.getResults().get(0);
                                    if(f.getCurrentState()==2){
                                        isCut=1;
                                    }
                                    else{
                                        isCut=2;
                                    }
                                    BmobQuery<Fight> bmobQuery1=new BmobQuery<Fight>();
                                    f.setCurrentPeole(f.getCurrentPeole()-1);
                                    Log.e("refunde0",f.getObjectId());
                                    f.update(f.getObjectId(), new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null){
                                                Log.e("refunde","1");
                                            }
                                            else{
                                                Log.e("refunderr","1");
                                            }
                                        }
                                    });
                                }
                                else{
                                    Log.e("refunderr","0");
                                }
                            }
                        });
                        Order order=new Order();
                        order=trip.getOrder();
                        order.setObjectId(getItem(position).getObjectidOr());
                        Log.e("refunde3", order.getObjectId());
                        order.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    Log.e("refunde","3");
                                }
                                else{
                                    Log.e("refunderr","3");
                                }
                            }
                        });
                    }
                    else{
                        String bq1="select * from Fight where FLIGHT='"+getItem(position).getFlightNO()+"'";
                        Log.e("refunde0",getItem(position).getFlightNO());
                        new BmobQuery<Fight>().doSQLQuery(bq1, new SQLQueryListener<Fight>() {
                            @Override
                            public void done(BmobQueryResult<Fight> bmobQueryResult, BmobException e) {
                                if(e==null){
                                    Log.e("refund","0");
                                    Fight f=new Fight();
                                    f=bmobQueryResult.getResults().get(0);
                                    if(f.getCurrentState()==2){
                                        isCut=1;
                                    }
                                    else{
                                        isCut=2;
                                    }
                                    BmobQuery<Fight> bmobQuery1=new BmobQuery<Fight>();
                                    f.setCurrentPeole(f.getCurrentPeole()-1);
                                    Log.e("refunde0",f.getObjectId());
                                    f.update(f.getObjectId(), new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null){
                                                Log.e("refunde","1");
                                            }
                                            else{
                                                Log.e("refunderr","1");
                                            }
                                        }
                                    });
                                }
                                else{
                                    Log.e("refunderr","0");
                                }
                            }
                        });
                        String bq2="select * from USER where name='"+getItem(position).getAccount()+"'";
                        Log.e("refunde2",getItem(position).getAccount());
                        new BmobQuery<USER>().doSQLQuery(bq2, new SQLQueryListener<USER>() {
                            @Override
                            public void done(BmobQueryResult<USER> bmobQueryResult, BmobException e) {
                                if(e==null){
                                    final List<USER> Users=bmobQueryResult.getResults();
                                    BmobQuery<USER> bmobQuery1=new BmobQuery<USER>();
                                    Users.get(0).setMoney(Users.get(0).getMoney()+trip.getPrice());
                                    Users.get(0).update(Users.get(0).getObjectId(), new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if(e==null){
                                                Log.e("refunde","2");
                                            }
                                            else{
                                                Log.e("refunderr","2");
                                            }
                                        }
                                    });
                                }
                                else{
                                }
                            }
                        });
                        Order order=new Order();
                        order=trip.getOrder();
                        order.setObjectId(getItem(position).getObjectidOr());
                        Log.e("refunde3", order.getObjectId());
                        order.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    Log.e("refunde","3");
                                }
                                else{
                                    Log.e("refunderr","3");
                                }
                            }
                        });
                    }
                }
                else{
                    Log.e("refunderr","0");
                }
            }
        });

    }
}
